//本模块将wx的get,post方法转化成promise
function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        //成功
        resolve(res)
      }
      obj.fail = function (res) {
        //失败
        reject(res)
      }
      fn(obj)
    })
  }
}

function wxPromisify2(fn, obj = {}) {
  return new Promise((resolve, reject) => {
    obj.success = function (res) {
      //成功
      resolve(res)
    }
    obj.fail = function (res) {
      //失败
      
      reject(res)
    }
    fn(obj)
  })
}

/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data, contentType) {
  var params = {
    url: url,
    method: 'GET',
    data: data,
    header: {
      'Content-Type': contentType || 'application/x-www-form-urlencoded'
    }};
  return wxPromisify2(wx.request, params);

}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(url, data, contentType) {
  var params = {
    url: url,
    method: 'POST',
    data: data,
    header: {
      'Content-Type': contentType || 'application/x-www-form-urlencoded'
    }};
  return wxPromisify2(wx.request, params);
}

module.exports = {
  post: postRequest,
  get: getRequest
}
